package com.llkj.safeearth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.llkj.safeearth.httpUtils.HttpMethod;
import com.llkj.safeearth.keepalive.KeepingAliveManager;
import com.llkj.safeearth.utils.SpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;

import static com.llkj.safeearth.LocationService.ACTION_LOCATION_CHANGED;
import static com.llkj.safeearth.LocationService.EXTRA_LOCATION;
import static com.llkj.safeearth.httpUtils.HttpMethod.HOME_INDEX;

public class MainActivity extends BaseActivity {

	@BindView(R.id.webView)
	WebView webView;
	@BindView(R.id.progressBar)
	ProgressBar progressBar;
	private WebSettings settings;
	private String url = HOME_INDEX;
	private String title = "";
	private String webViewTitle = "";
	private String content = "";
	private String originalUrl;
	private boolean canShare;
	private boolean needTitle;//是否强制显示title,如果为false,则title可空可不空.如果为true,则一定显示title,title为空时,去h5里取title标签里的内容.
	private boolean isUrl;
	private String messegeUrl = "https://aqdq.apptiming.com/index.php?r=app/homepage/noticedelt&id=";
	private String mCurrentUrl;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_main;
	}

	@Override
	protected void onPause() {
		super.onPause();
//		webView.onPause();
//		webView.pauseTimers();

	}

	@Override
	public void onResume() {
		super.onResume();
		webView.onResume();
		webView.resumeTimers();

	}

	protected void initView() {
		super.initView();
		settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		// 设置允许JS弹窗
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setAllowFileAccess(true);
		settings.setDatabaseEnabled(true);
		//webview定位相关设置
		settings.setGeolocationEnabled(true);
		settings.setDomStorageEnabled(true);
		settings.setSaveFormData(false);
		settings.setAppCacheEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		settings.setLoadWithOverviewMode(true);
		settings.setUseWideViewPort(true);
		webView.setWebChromeClient(new MywebChromeClient());
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setWebViewClient(new MyWebClicne());
		//在js中调用本地java方法
		webView.addJavascriptInterface(new JsInterface(this), "appdowhat");

		KeepingAliveManager.getAliveManagerIntance().registerLockScreenBrocastReciever();

	}

	protected void initData() {
		super.initData();
		mCurrentUrl = url;
		webView.loadUrl(url);
		Log.e("Log", "=====initData()========" + mPermission);
		registerMessageReceiver();  // used for receive msg
	}

	@Override
	public void onBackPressed() {
		if (webView.canGoBack()) {
			webView.goBack();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void onLowMemory() {
		Log.e("Log", "=====onLowMemory()====");
		super.onLowMemory();
	}

	@Override
	protected void onDestroy() {
		Log.e("Log", "=====onDestroy()====");
		if (webView != null) {
			webView.clearHistory();
			webView.clearSslPreferences();
			webView.clearFormData();
			webView.clearCache(true);
			webView.clearView();
			((ViewGroup) webView.getParent()).removeView(webView);
			webView.destroy();
			webView = null;
		}
		JPushInterface.deleteAlias(mContext, 0);
		LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
		super.onDestroy();
	}

	private class JsInterface {
		private Context mContext;

		public JsInterface(Context context) {
			this.mContext = context;
		}

		//在js中调用window.AndroidWebView.xxx(name)，便会触发此方法。
		@JavascriptInterface
		public void userid(String name) {
			//此处为 js 返回的结果
			Log.e("Log", "=====uid=====" + name);
			sputil.put(SpUtil.USER_ID,name);
			JPushInterface.setAlias(mContext, 0, name);

			if(LocationService.mLastLocation != null){
				HttpMethod.updataeLocation(MainActivity.this,null,sputil.getString(SpUtil.USER_ID)
						,String.valueOf(LocationService.mLastLocation.getLatitude()),String.valueOf(LocationService.mLastLocation.getLongitude()),null);
			}
		}

		@JavascriptInterface
		public void baojing(String type){
			if(LocationService.mLastLocation != null){
				HttpMethod.updataeLocation(MainActivity.this,null,sputil.getString(SpUtil.USER_ID)
						,String.valueOf(LocationService.mLastLocation.getLatitude()),String.valueOf(LocationService.mLastLocation.getLongitude()),type);
			}
		}

		@JavascriptInterface
		public void clearCache() {
			Toast.makeText(mContext, "清除成功", Toast.LENGTH_SHORT).show();
		}

		@JavascriptInterface
		public void toShare(String url) {
			//创建分享Intent
			Intent sharedIntent = new Intent();
			//设置动作为Intent.ACTION_SEND
			sharedIntent.setAction(Intent.ACTION_SEND);
			//设置为文本类型
			sharedIntent.setType("text/*");
			sharedIntent.putExtra(Intent.EXTRA_TEXT, url); //设置要分享的内容
			startActivity(Intent.createChooser(sharedIntent, "分享到："));
		}

		@JavascriptInterface
		public void enablePush(int i) {
			//此处为 js 返回的结果
			if (i == 0) {
				JPushInterface.stopPush(mContext);
			} else {
				JPushInterface.resumePush(mContext);
			}
		}
	}

	private String transferUrl(String url) {
		if (!url.startsWith("http://") && !url.startsWith("https://")
				&& !url.startsWith("ftp://")) {
			return "http://" + url;
		}
		return url;
	}

	class MyWebClicne extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.e("Log", "======shouldOverrideUrlLoading=======" + mPermission);
			if (url.startsWith("http:") || url.startsWith("https:")) {
				mCurrentUrl = url;
				view.loadUrl(mCurrentUrl);
				return true;
			}

//			// Otherwise allow the OS to handle things like tel, mailto, etc.
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			startActivity(intent);
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			progressBar.setVisibility(View.GONE);
			webViewTitle = view.getTitle();
			if (needTitle && TextUtils.isEmpty(title) && !TextUtils.isEmpty(webViewTitle)) {
			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
									String description, String failingUrl) {
			progressBar.setVisibility(View.GONE);
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			Log.e("Log", "======onReceivedSslError=======" + mPermission);
			handler.proceed();
		}

	}

	class MywebChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
								 final JsResult result) {
			// 弹窗处理
			AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
					.setTitle(R.string.app_name).setMessage(message)
					.setPositiveButton("ok", new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							result.confirm();
						}
					});
			b2.setCancelable(false);
			b2.create();
			b2.show();
			return true;
		}

		@Override
		public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
			Log.e("Log", "=====onGeolocationPermissionsShowPrompt========" + mPermission);
			callback.invoke(origin, true, false);
			super.onGeolocationPermissionsShowPrompt(origin, callback);
		}

		@Override
		public void onReceivedIcon(WebView view, Bitmap icon) {
			super.onReceivedIcon(view, icon);
		}
	}


	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String NOTIFICATION_RECEIVED_ACTION = "com.example.jpushdemo.NOTIFICATION_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		filter.addAction(NOTIFICATION_RECEIVED_ACTION);
		LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
					String messge = intent.getStringExtra(KEY_MESSAGE);
					String extras = intent.getStringExtra(KEY_EXTRAS);
					StringBuilder showMsg = new StringBuilder();
					showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
					if (!TextUtils.isEmpty(extras)) {
						showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
					}
//					Toast.makeText(MainActivity.this, showMsg.toString(), Toast.LENGTH_SHORT).show();
					Log.e("", showMsg.toString());
					final AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
							.setTitle(R.string.app_name).setMessage(messge)
							.setPositiveButton("ok", new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
					b2.setCancelable(false);
					b2.create();

					AlertDialog show = b2.show();

				} else if (NOTIFICATION_RECEIVED_ACTION.equals(intent.getAction())) {//通知
					Bundle bundle = intent.getBundleExtra("message");
					String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
					Log.e("Log","======="+extras);
					try {
						JSONObject extraJson = new JSONObject(extras);
						if (extraJson.length() > 0) {
							webView.loadUrl(messegeUrl+extraJson.getString("type"));
						}
					} catch (JSONException e) {

					}
				}
			} catch (Exception e) {
			}
		}
	}

}
